class DirectoryVisualizer {
    constructor() {
        this.isProcessing = false;
        this.statusInterval = null;
        this.pathDisplay = document.getElementById('pathDisplay');
        this.executeBtn = document.getElementById('executeBtn');
        this.dirPath = null;
        this.formatSize = this.formatSize.bind(this);
        this.initElements();
        this.initEvents();
        this.startPolling();
        this.initExecuteHandler();
    }

    initExecuteHandler() {
        this.executeBtn.addEventListener('click', () => this.handleExecute());
    }

    formatSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    initElements() {
        this.selectBtn = document.getElementById('selectBtn');
        this.dirInput = document.getElementById('dirInput');
        this.fileList = document.getElementById('fileList');
        this.intermediateGallery = document.getElementById('intermediateGallery');
        this.finalGallery = document.getElementById('finalGallery');
    }

    initEvents() {
        this.selectBtn.addEventListener('click', () => this.dirInput.click());
        this.dirInput.addEventListener('change', e => this.handleDirectory(e));
    }

    async handleDirectory(event) {
        const files = Array.from(event.target.files);
        const csvFiles = files.filter(f => f.name.endsWith('.txt'));

        // 直接使用webkitRelativePath获取目录名
        if (files.length > 0) {
            const pathSegments = files[0].webkitRelativePath.split('/');
            this.dirPath = pathSegments[0];
            this.pathDisplay.value = this.dirPath;
        } else {
            this.pathDisplay.value = '';
            this.dirPath = null;
        }

        this.renderFileList(csvFiles);
    }

    async handleExecute() {
        if (!this.pathDisplay.value) {
            alert('请先选择目录');
            return;
        }
        if (this.isProcessing) return;

        try {
            this.toggleProcessingUI(true);
            const executePromise = fetch('/api/execute', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ path: this.pathDisplay.value })
            });

            this.startStatusPolling();
            const response = await executePromise;
            if (!response.ok) throw new Error(`执行失败: ${response.status}`);

        } catch (error) {
            this.toggleProcessingUI(false);
            console.error('请求异常:', error);
            alert(`操作失败: ${error.message}`);
        }
    }

    startStatusPolling() {
        this.checkStatus();
        this.statusInterval = setInterval(() => {
            this.checkStatus();
        }, 2000);
    }

    async checkStatus() {
        try {
            const res = await fetch('/api/status');
            if (!res.ok) throw new Error('状态查询失败');

            const { status } = await res.json();
            this.updateStatusDisplay(status);

            if (status === 2) {
                clearInterval(this.statusInterval);
                setTimeout(() => {
                    this.toggleProcessingUI(false);
                    this.loadImages();
                }, 1000);
            }
        } catch (error) {
            console.error('状态检查错误:', error);
            clearInterval(this.statusInterval);
            this.toggleProcessingUI(false);
        }
    }

    toggleProcessingUI(show) {
        const overlay = document.getElementById('processingOverlay');
        overlay.style.display = show ? 'flex' : 'none';
        document.body.classList.toggle('processing', show);
        this.isProcessing = show;
    }

    updateStatusDisplay(statusCode) {
        const statusMap = {
            0: { text: '预处理数据中...', color: '#2196F3' },
            1: { text: '飞行评估计算中...', color: '#4CAF50' },
            2: { text: '评估完成！', color: '#673AB7' }
        };

        const statusText = document.getElementById('statusText');
        const spinner = document.querySelector('.loading-spinner');

        statusText.textContent = statusMap[statusCode].text;
        spinner.style.borderTopColor = statusMap[statusCode].color;

        if (statusCode === 2) {
            spinner.style.borderTopColor = '#FF9800';
            setTimeout(() => {
                spinner.style.display = 'none';
            }, 1000);
        }
    }

    renderFileList(files) {
        this.fileList.innerHTML = files
            .map(file => `
                <li class="file-item">
                    <div class="filename">📄 ${file.name}</div>
                    <div class="meta">
                        大小: ${(file.size/1024).toFixed(1)}KB<br>
                        类型: ${file.type || 'text/csv'}
                    </div>
                </li>
            `)
            .join('');
    }

    async loadImages() {
        try {
            const res = await fetch('/api/images');
            const data = await res.json();

            if (data.error) {
                console.error('图片加载失败:', data.error);
                return;
            }

            this.renderGallery(data.intermediate, 'intermediateGallery');
            this.renderGallery(data.final, 'finalGallery');

        } catch (error) {
            console.error('请求失败:', error);
        }
    }

    renderGallery = (images, targetId) => {
        const gallery = document.getElementById(targetId);
        gallery.innerHTML = images
            .map(img => `
                <div class="image-card">
                    <div class="meta">文件名: ${img.filename}</div>
                    <img
                        src="${img.url}"
                        alt="${img.filename}"
                        loading="lazy"
                        data-src="${img.url}"
                    >
                    <div class="meta">文件大小: ${this.formatSize(img.size)}</div>
                </div>
            `).join('');

        this.addImageClickHandlers(gallery);
    }

    addImageClickHandlers(container) {
        const images = container.querySelectorAll('img');
        images.forEach(img => {
            img.addEventListener('click', (e) => {
                this.showModalImage(e.target.dataset.src || e.target.src);
            });
        });
    }

    showModalImage(src) {
        const modal = document.getElementById('imageModal');
        const modalImg = document.getElementById('modalImage');
        modalImg.src = src;
        modal.style.display = "block";

        document.querySelector('.close').onclick = () => {
            modal.style.display = "none";
        }
        modal.onclick = (e) => {
            if (e.target === modal) {
                modal.style.display = "none";
            }
        }
    }

    startPolling() {
        setInterval(() => {
            this.loadImages();
        }, 5000);
    }

    destroy() {
        clearInterval(this.statusInterval);
    }
}

document.addEventListener('DOMContentLoaded', () => {
    new DirectoryVisualizer();
});
